package org.zyj.io.protocal.custom;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.zyj.io.protocal.Message;

/**
 * 完全自己实现 Message 转 ByteBuf
 */
public class MessageEncoder extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        ByteBuf buf = ctx.alloc().ioBuffer();
        if (msg instanceof Message) {
            Message myMessage = (Message) msg;
            encode(ctx, myMessage, buf);
            ctx.writeAndFlush(buf, promise);
        }
    }

    /**
     * 粗糙的实现, 这个请求体设计的很垃圾, 别学
     * 此例的目的仅仅是为了展示Netty的pipeline中数据的流转
     */
    private void encode(ChannelHandlerContext ctx, Message myMessage, ByteBuf buf) {
        //1. 计算请求体body长度
        int length = myMessage.getBody().length;
        //2. 按照协议规则写入报文
        buf.writeInt(length);
        buf.writeInt(myMessage.getVersion());
        buf.writeInt(myMessage.getOpCode());
        buf.writeInt(myMessage.getStreamId());
        buf.writeBytes(myMessage.getBody());
    }
}
